package com.zlcx.tz.live.repository;

import com.zlcx.tz.live.domain.TimeLearnRoomSeatsDO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import javax.persistence.LockModeType;
import java.util.List;

/**
 * @author anjl
 */
@Repository
public interface TimeLearnRoomSeatsRepository extends JpaRepository<TimeLearnRoomSeatsDO, Long>, JpaSpecificationExecutor<TimeLearnRoomSeatsDO> {

    Integer countByRoomIdAndUserIdNotNull(Long roomId);

    /**
     * 占座，对数据行进行加锁，防止出现脏读
     * @param seatId seatId
     */
    @Lock(value = LockModeType.PESSIMISTIC_WRITE)
    TimeLearnRoomSeatsDO findById(Long seatId);

    List<TimeLearnRoomSeatsDO> findByRoomId(Long roomId);

    TimeLearnRoomSeatsDO findByUserId(Long userId);

    @Query(value = "select * from `tz_time_learn_room_seats` t \n" +
            "where t.user_id is not null and timestampdiff(MINUTE,t.seating_time,now())  > t.minutes",nativeQuery = true)
    List<TimeLearnRoomSeatsDO> findExpireUsers();

    @Query(value = "select sum(t.used_seats_num) from `tz_time_learn_room` t " ,nativeQuery = true)
    Integer sumUsedSeatsNum();
}
